// 购物车
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
  m_id:"",
  goods:[],
  // 已经选择商品的数量
  num:0,
  // 已经选择商品的总价
  total:0,
  // 已经选择的cart_id数组
  cart:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var m_id = app.globalData.user.m_id;
    if(m_id == undefined){
      app.getMid(function(){
        this.getProduct()
      }.bind(this)) 
    } else{
      this.getProduct()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    var m_id = app.globalData.user.m_id;
    var cart = this.data.cart;
    this.setData({
      m_id: m_id
    })
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Cart/cartList',
      data: {
        m_id: m_id
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      success: function (res) {

        var goods = res.data.data;
        that.setData({
          goods: goods
        })
        if (goods == "") {
          that.setData({
            goods: goods,
            num: 0,
            cart: "",
            total:0
          })
        } else {
          var num = 0;
          var total = 0;
          var cartNew = []
          goods[0].product.map(function (val) {
            for (var i = 0, length = cart.length; i < length; i++) {
              if (val.cart_id == cart[i]) {
                val.checked = true;
                total = Number(total) + Number(val.price);
                num = Number(num) + 1;
                cartNew.push(val.cart_id)
              }
            }
          })
          // 把当前选择的购物车ID，赋值给data（针对支付完成后，返回当前页面）
          cart = cartNew
          // 判断之前是否选择过，如果选择过，显示出来
          that.setData({
            goods: goods,
            num: num,
            cart: cart,
            total:total
          })
        }
        wx.stopPullDownRefresh()
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
        })
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    return {
      title: app.globalData.name,
      path: "/pages/shouye/shouye",
      imageUrl: app.globalData.headPic
    }
  },
  /**
   * 获取商品列表
   */
  getProduct:function(){
    var m_id = app.globalData.user.m_id;
    console.log("m_id")
    var that = this;
    var cart = this.data.cart;
    this.setData({
      m_id: m_id
    })
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Cart/cartList',
      data: {
        m_id: m_id
      },
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      success: function (res) {

        var goods = res.data.data;
        that.setData({
          goods: goods
        })
        if (goods == "") {
          that.setData({
            goods: goods,
            num: 0,
            cart: "",
            total: 0
          })
        } else {
          var num = 0;
          var total = 0;
          var cartNew = []
          goods[0].product.map(function (val) {
            for (var i = 0, length = cart.length; i < length; i++) {
              if (val.cart_id == cart[i]) {
                val.checked = true;
                total = Number(total) + Number(val.price);
                num = Number(num) + 1;
                cartNew.push(val.cart_id)
              }
            }
          })
          // 把当前选择的购物车ID，赋值给data（针对支付完成后，返回当前页面）
          cart = cartNew
          // 判断之前是否选择过，如果选择过，显示出来
          that.setData({
            goods: goods,
            num: num,
            cart: cart,
            total: total
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
        })
      }
    })
  },
  /**
   * 选择商品
   */
  choose:function(e){
    var that = this;
      var cart_id = e.currentTarget.dataset.id;
      var goods = this.data.goods;
      var product = goods[0].product;
      var cart = this.data.cart;
      var num = this.data.num;
      var total = this.data.total;
      // 根据cart_id获得商品属性
      for(var i=0,length=product.length;i<length;i++){

        if(product[i].cart_id == cart_id){
          // 判断原先是否选中
          if(product[i]['checked'] == true){
            for (var j = 0, l = cart.length; j < l; j++) {
              if (cart[j] == cart_id) {
                cart.splice(j, 1);
              }
            }
            product[i]['checked'] = false; 
            that.setData({
              goods:goods,
              cart:cart
            })
            that.changeTotal()
          }else{
            // 原先未选中，添加选中
            product[i]['checked'] = true;
            cart.push(cart_id)
            that.setData({
              goods: goods,
              cart: cart
            })
            that.changeTotal()
          }
        }
      }
  },
  /**
 * 全选
 */
  chooseAll: function () {
    var goods = this.data.goods;
    var product = goods[0].product;
    var cart = this.data.cart;
    var num = this.data.num;
    var total = this.data.total;
    if(cart == ""){
      product.map(function (val) {
        cart.push(val.cart_id)
        val.checked = true;
        num = Number(num) + Number(val.num)
        total = Number(total) + (Number(val.num)*Number(val.price))
      })
    }else{
      cart =[]
      product.map(function (val) {
        val.checked = false;
      })
      num = 0;
      total=0;
    }
    this.setData({
      goods:goods,
      cart:cart,
      num: num,
      total:total
    })
  },

  /**
   * 加号
   */
  add:function(e){
    var that = this;
    var m_id = app.globalData.user.m_id;
    var cart_id = e.currentTarget.dataset.id;
    var goods = this.data.goods;
    var product = goods[0].product;
    var i = 0, length = product.length
    for(i;i<length;i++){
      if(product[i].cart_id == cart_id){
        break
      }
    }
    this.changeCart(cart_id,i,1)
  },
/**
 * 减号
 */
mini:function(e){
  var that = this;
  var m_id = app.globalData.user.m_id;
  var cart_id = e.currentTarget.dataset.id;
  var goods = this.data.goods;
  var product = goods[0].product;
  var i = 0, length = product.length
  for (i; i < length; i++) {
    if (product[i].cart_id == cart_id) {
      break
    }
  }
  // 判断是否为1，如果是1，执行删除，如果不是执行减号
  var shopNum = product[i].num;
  if(shopNum == 1){
    wx.showModal({
      title: '提示',
      content: '确定删除此商品？',
      success:function(res){
       if(res.confirm){
         wx.request({
           url: app.globalData.yuming + 'merchant.php/Api/Cart/delCart',
           data: {
             cart_id: cart_id
           },
           header: {
             "content-type": "application/x-www-form-urlencoded"
           },
           method: "POST",
           success: function (res) {
            //  删除goods中的当前物品
            product.splice(i,1)
            that.setData({
              goods:goods
            })
            // 改变选中的数量和价格
            that.changeTotal()
           },
           fail: function (res) {
             wx.showModal({
               title: '提示',
               content: res.data.message,
               showCancel: false
             })
           }
         })
       }
       
      },
      fail:{
        
      }
    })
  }else{
    this.changeCart(cart_id, i, -1)
  }
},
/**
 * 改变购物车(传参：cart_id购物车id，i是product中第i个，n为+-1,分别代表加减)
 */
changeCart:function(cart_id,i,n){
  var that = this;
  var goods = this.data.goods;
  var product = goods[0].product;
  var num = product[i].num;
  var attr = product[i].attr_val_id;
  if(attr == undefined){
    attr =""
  }
  // 修改购物车
  wx.request({
    url: app.globalData.yuming + 'merchant.php/Api/Cart/editCart',
    data: {
      cart_id: cart_id,
      num: Number(num) + n,
      attr: attr
    },
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
    method: "POST",
    success: function (res) {
      var newNum = res.data.data;
      if (res.data.message == "操作成功") {
        product[i].num = newNum;
      }else{
        product[i].num = newNum;
        wx.showModal({
          title: '提示',
          content: res.data.message,
          showCancel: false
        })
      }
     
      that.setData({
        goods:goods
      })
      that.changeTotal()
    }
  })
},
/**
 *改变当前选中的数量和总价
 */
changeTotal:function(){
    var goods = this.data.goods;
    var product = goods[0].product;
    var num = 0;
    var total = 0;
    product.map(function(val){
      if(val.checked == true){
        num = Number(num) + Number(val.num)
        total = Number(total) + Number(val.num*val.price)
      }
    })
    this.setData({
      num:num,
      total: total
    })
},
/**
 * 结算
 */
  account:function(){
    var that = this;
    var cart = this.data.cart;
    if(cart == ""){
      wx.showModal({
        title: '提示',
        content: '请选择商品',
        showCancel:false
      })
    }else{
      var cart_id = cart[0];
      for (var i = 1, length = cart.length; i < length; i++) {
        cart_id = cart_id + "," + cart[i]
      }
      var goods= that.data.goods;
      var shop_id = goods[0].shop_id;
      var storage = ["1",cart_id,shop_id]
      wx.setStorage({
        key: 'storage',
        data: storage,
        success:function(res){
         wx.navigateTo({
           url: '/order/orderlist/orderlist',
         })
        }
      })
      
    }
    
  }
})
